﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Windows;

namespace Common.Tool
{
    public class ProgressBarHandle
    {
        private ProgressBar progressBar = null;
        private System.Threading.Thread ts = null;

        public void SetProgressBarHandle(ProgressBar Progressbar)
        {
            progressBar = Progressbar;
        }

        public void Exit()
        {
            if (null != ts)
            {
                ts.Abort();
            }
        }

        /**
         * \brief 进度条显示初始化
         * 
         * \param[in] count 进度条显示最大值
         * \retval void 空
         */
        public void InitProgressBar(int count)
        {
            progressBar.Value = 0;
            progressBar.Maximum = count;
            progressBar.Visibility = Visibility.Visible;
        }

        //创建进度条更新的线程
        public void CreateProgressThread(int fileCount)
        {
            if (null != ts)
            {
                ts.Abort();
            }
            ts = new System.Threading.Thread(UpdateProgress);
            System.Threading.Thread.Sleep(100);
            ts.Start(fileCount);
            DoEvents();
        }

        public void UpdateProgress(object value)
        {
            Action<int> newAction = new Action<int>(UpdateProgressThread);
            progressBar.Dispatcher.Invoke(newAction, (int)value);//同步执行指定的委托
            System.Threading.Thread.Sleep(100);
        }

        public void UpdateProgressThread(int fileCount)
        {
            progressBar.Value = fileCount;
            if (fileCount > progressBar.Maximum)
            {
                progressBar.Value = progressBar.Maximum;
            }
        }

        //扩展方法进行界面刷新
        public void DoEvents()
        {
            DispatcherFrame frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                new DispatcherOperationCallback(ExitFrames), frame);
            Dispatcher.PushFrame(frame);
        }

        public static object ExitFrames(object f)
        {
            ((DispatcherFrame)f).Continue = false;
            return null;
        }
    }
}
